package com.situ.orderingsystem.servlet;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import com.situ.orderingsystem.global.Global;
import com.situ.orderingsystem.model.Employee;
import com.situ.orderingsystem.model.EmployeeSerchBean;
import com.situ.orderingsystem.service.EmpoloyeeService;
import com.situ.orderingsystem.service.impl.EmployeeServiceImpl;
import com.situ.orderingsystem.utils.BeanFactory;
import com.situ.orderingsystem.utils.PaginateInfo;
import com.situ.orderingsystem.utils.Servlets;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@WebServlet("/employee/*")
public class EmployeeServlet extends HttpServlet {
    private final EmpoloyeeService service = BeanFactory.getBean(EmployeeServiceImpl.class);
    private HttpServletResponse resp;
    private HttpServletRequest req;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        String context = req.getContextPath();
        String action = url.replace(context, "");
        if (action.equals("/employee/list")) {
            req.getRequestDispatcher("/WEB-INF/jsp/employee/list.jsp").forward(req, resp);
        } else if (action.equals("/employee/add")) {
            HttpSession session =req.getSession();
            Employee employee =(Employee)session.getAttribute("employee");
            String error = (String)session.getAttribute("error");
            if(employee != null){
                req.setAttribute("empoloyee",employee);
                session.removeAttribute("employee");
                req.setAttribute("error",error);
                session.removeAttribute("error");
            }
            req.getRequestDispatcher("/WEB-INF/jsp/employee/add.jsp").forward(req, resp);
        }else  if(action.equals("/employee/edit")){
            String id = req.getParameter("id");
            try{
                Employee emp = service.searchById(Integer.parseInt(id));
                emp.setId(Integer.parseInt(id));

                if(emp == null){
                    req.setAttribute("error","你要修改的顾客不存在");
                }
                else{
                    req.setAttribute("employee",emp);
                }
            }catch (NumberFormatException e) {
                req.setAttribute("error", "请指定要修改的学生的编号");
            }
            req.getRequestDispatcher("/WEB-INF/jsp/employee/edit.jsp").forward(req,resp);
        }
        else if(action.equals("/employee/export")){
            export();
        }
        else if(action.equals("/employee/export1")){
            export1();
        }
        else if(action.equals("/employee/update")){
            update();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.resp = resp;
        this.req = req;
        String url = req.getRequestURI();
        String context = req.getContextPath();
        String action = url.replace(context, "");
        if (action.equals("/employee/list")) {
            search();
        } else if (action.equals("/employee/delete")) {
            delete();
        } else if (action.equals("/employee/add")) {
            save();
        }else  if(action.equals("/employee/edit")){
            edit();
        } else if (action.equals("/employee/import")) {
            update();
        }



    }

    private void search() {
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        String empId = req.getParameter("empId");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String description = req.getParameter("description");

        EmployeeSerchBean esb = new EmployeeSerchBean();
        if (StringUtils.hasText(empId)) {
            esb.setEmpId(empId);
        }
        if (StringUtils.hasText(name)) {
            esb.setName(name);
        }
        if (StringUtils.hasText(phone)) {
            esb.setPhone(phone);
        }
        if (StringUtils.hasText(description)) {
            esb.setDescription(description);
        }
        int iPageNo = 1;
        if (StringUtils.hasText(pageNo)) {
            iPageNo = Integer.parseInt(pageNo);
        }
        int iPageSize = 10;
        if (StringUtils.hasText(pageSize)) {
            iPageSize = Integer.parseInt(pageSize);
        }
//            从数据库中查询
        PaginateInfo pi = new PaginateInfo(iPageNo, iPageSize);

        List<Employee> elist = service.findAll(esb, pi);

        //响应ajax
        String json = JSON.toJSONString(Map.of("elist", elist, "pi", pi));
        Servlets.renderJson(json, resp);
    }

    private void delete() {
        String[] strIds = req.getParameterValues("ids");
        Integer[] ids = Stream.of(strIds).map(Integer::valueOf).toArray(Integer[]::new);
        try {
            int rows = service.deleteByIds(ids);
            Servlets.renderJson(Map.of("success", true, "msg", "删除成功", "rows", rows), resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("============");
            Servlets.renderJson(Map.of("success", false, "error", "删除失败"), resp);
        }

    }

    private void save() throws IOException {
        String empId = req.getParameter("emp_id");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String desciption = req.getParameter("description");

        HttpSession session = req.getSession();

        boolean passed = true;
        List<String> errors = new ArrayList<>();

        //校验
        Employee employee = new Employee();

        if (!StringUtils.hasText(empId)) {
            passed = false;
            errors.add("编号不可为空");
        }
        employee.setEmpId(empId);
        if (!StringUtils.hasText(name)) {
            passed = false;
            errors.add("姓名不可为空");
        }
        employee.setName(name);
        if (!StringUtils.hasText(phone)) {
            passed = false;
            errors.add("电话不可为空");
        }
        employee.setPhone(phone);
        employee.setDescription(desciption);


        if (!passed) {
            session.setAttribute("employee", employee);
            String error = errors.stream().collect(Collectors.joining(","));
            session.setAttribute("error", error);
            resp.sendRedirect(req.getContextPath()+"/employee/add");
            return;
        }
        boolean sava = service.save(employee);

        if(sava){
            resp.sendRedirect(req.getContextPath()+"/employee/list");
        }else{
            session.setAttribute("employee",employee);
            session.setAttribute("error","保存顾客信息失败");
            resp.sendRedirect(req.getContextPath()+"/employee/add");
        }
    }
    private void edit(){
        String id = req.getParameter("empId");
//        System.out.println(id+"===========");
        String empId = req.getParameter("emp_id");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String description = req.getParameter("description");
        HttpSession session = req.getSession();

        //校验
        Employee employee = new Employee();
        if (!StringUtils.hasText(id)) {
            Servlets.renderJson(Map.of("error", "要修改的学生编号不可为空"), resp);
            return;
        }

        try {
          employee.setId(Integer.valueOf(id));
        }catch (NumberFormatException e) {
            Servlets.renderJson(Map.of("error", "要修改的学生编号不正确"), resp);
            return;
        }

        if (!StringUtils.hasText(empId)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }

        employee.setEmpId(empId);
        if (!StringUtils.hasText(name)) {
            Servlets.renderJson(Map.of("error", "编号不可为空"), resp);
            return;
        }
        employee.setName(name);
        if (!StringUtils.hasText(phone)) {
            Servlets.renderJson(Map.of("error", "电话不可为空"), resp);
            return;
        }
        employee.setPhone(phone);
        employee.setDescription(description);

        System.out.println(employee.toString());
        boolean b = service.update(employee);
        System.out.println(b);
        if(b){
            Servlets.renderJson(Map.of("success",true),resp);
        }
        else {
            Servlets.renderJson(Map.of("success",false,"error","保存学生信息失败"),resp);
        }



    }
    private void export(){
        List<Employee> elist = service.findAll2();
        resp.setContentType("application/vnd.ms-excel");

        resp.setCharacterEncoding("utf-8");

        try{
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String fileName = URLEncoder.encode("顾客列表导出" + format, "UTF-8").replaceAll("\\+", "%20");
            resp.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //导出
            EasyExcel.write(resp.getOutputStream(), Employee.class).sheet("模板").doWrite(elist );

        }catch (Exception e) {
            e.printStackTrace();

        }
    }
    private void export1(){
        String str = req.getParameter("ids");
        String[] strIds =str.split(",");
        Integer[] ids = Stream.of(strIds).map(Integer::valueOf).toArray(Integer[]::new);
        List<Employee> elist = new ArrayList<>();
        for(Integer id:ids){
            elist.add(service.searchById(id));
        }
        resp.setContentType("application/vnd.ms-excel");

        resp.setCharacterEncoding("utf-8");

        try{
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String fileName = URLEncoder.encode("顾客列表导出" + format, "UTF-8").replaceAll("\\+", "%20");
            resp.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //导出
            EasyExcel.write(resp.getOutputStream(), Employee.class).sheet("模板").doWrite(elist );

        }catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void update() throws IOException, ServletException {
        if (req.getMethod().equalsIgnoreCase("get")) {
            req.getRequestDispatcher("/WEB-INF/jsp/import.jsp").forward(req, resp);
        } else {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
            //jakartaEE需要手动实现参数类型
            List<FileItem> items = sfu.parseRequest(req);

            for (FileItem fi : items) {
                if (!fi.isFormField()) {
                    if (fi.getSize() > 0) {
                        InputStream is = fi.getInputStream();//上传文件的输入流
                        EasyExcel.read(is, Employee.class, new UploadDataListener()).sheet().doRead();
                    }
                }
            }
        } catch (FileUploadException | IOException e) {
            e.printStackTrace();
        }
        System.out.println("读入成功");
        resp.sendRedirect(req.getContextPath() + "/employee/list");


        }
    }
    private static class UploadDataListener implements ReadListener<Employee> {
        private final EmpoloyeeService service = BeanFactory.getBean(EmployeeServiceImpl.class);
        private final List<Employee> list = new ArrayList<>();

        @Override
        public void invoke(Employee employee, AnalysisContext analysisContext) {
            list.add(employee);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            System.out.println("读取结束");
            for (Employee employee : list) {
                service.save(employee);
            }
        }
    }
}
